import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_web_socket/util/toast_util.dart';
import 'package:flutter_web_socket/util/web_socket_manager.dart';

import 'model/msg.dart';

/// WebSocket页面
class WebSocketPage extends StatefulWidget {
  /// 连接地址
  final String _url;

  const WebSocketPage({super.key, required String url}) : _url = url;

  @override
  State<StatefulWidget> createState() {
    return WebSocketPageState();
  }
}

class WebSocketPageState extends State<WebSocketPage> {
  /// WebSocket管理类
  final WebSocketManager _webSocketManager = WebSocketManager();

  /// TextField操作控制器
  final TextEditingController _editingController = TextEditingController();

  /// ListView的滚动控制器
  final ScrollController _scrollController = ScrollController();

  /// 消息列表
  final List<Msg> _msgList = [];

  @override
  void initState() {
    super.initState();
    _webSocketManager.connect(widget._url).then((isConnect) {
      //连接成功，监听消息
      if (isConnect) {
        _webSocketManager.listen((msg) {
          //添加消息到列表中
          _addMsg2List(msg, false);
        }, onError: (error) {
          ToastUtil.toast("连接异常：${error.toString()}");
        });
      }
    });
  }

  @override
  void dispose() {
    //断开连接，销毁流对象
    _webSocketManager.dispose();
    super.dispose();
  }

  /// 添加消息到消息列表中
  void _addMsg2List(String msg, bool isMe) {
    setState(() {
      String msgText;
      if (isMe) {
        msgText = "我：$msg";
      } else {
        msgText = "服务器：$msg";
      }
      _msgList.add(Msg(
        isMe: isMe,
        msg: msgText,
        createTime: DateTime.now().millisecond,
      ));
    });
    //延迟300毫秒，再滚动到列表底部
    Future.delayed(const Duration(milliseconds: 300), () {
      _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
    });
  }

  /// 发送消息
  void _sendMsg(String msg) {
    if (msg.isEmpty) {
      ToastUtil.toast("请输入要发送的消息内容");
      return;
    }
    var isSendSuccess = _webSocketManager.sendMsg(msg);
    //发送成功
    if (isSendSuccess) {
      //添加消息到列表中
      _addMsg2List(msg, true);
      //清除输入框的内容
      _editingController.clear();
    } else {
      ToastUtil.toast("发送失败");
    }
  }

  /// 构建连接状态控件
  Widget _buildConnectStatusWidget() {
    return StreamBuilder<ConnectStatusEnum>(
      builder: (context, snapshot) {
        if (snapshot.data == ConnectStatusEnum.connect) {
          return StreamBuilder(
            builder: (context, newSnapshot) {
              //WebSocket发生错误，那么重连
              if (newSnapshot.hasError) {
                _webSocketManager.reconnect(widget._url);
              }
              return const Text(
                "连接状态：已连接",
              );
            },
            stream: _webSocketManager.getWebSocketChannelStream(),
          );
        } else if (snapshot.data == ConnectStatusEnum.connecting) {
          //连接中
          return Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const CupertinoActivityIndicator(
                animating: true,
                radius: 10,
              ),
              Container(
                margin: const EdgeInsets.only(left: 5.0),
                child: const Text("连接中..."),
              )
            ],
          );
        } else if (snapshot.data == ConnectStatusEnum.close) {
          return const Text(
            "连接状态：已关闭",
          );
        } else if (snapshot.data == ConnectStatusEnum.closing) {
          return const Text(
            "连接状态：关闭中",
          );
        }
        return const Text(
          "未连接",
        );
      },
      initialData: ConnectStatusEnum.close,
      stream: _webSocketManager.getSocketStatusStream(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
            onPressed: () {
              Navigator.pop(context, null);
            },
            icon: const Icon(Icons.arrow_back)),
        title: const Text("WebSocket测试"),
      ),
      body: Column(
        children: [
          //连接状态
          Column(
            children: [
              Container(
                height: 0.2,
                color: Colors.grey,
              ),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: _buildConnectStatusWidget(),
              ),
              Container(
                height: 0.2,
                color: Colors.grey,
              )
            ],
          ),
          Expanded(
            flex: 1,
            child: ListView.builder(
                controller: _scrollController,
                itemCount: _msgList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      // 如果是自己发的，则在右边
                      mainAxisAlignment: _msgList[index].isMe
                          ? MainAxisAlignment.end
                          : MainAxisAlignment.start,
                      children: [
                        Container(
                          padding: const EdgeInsets.all(15.0),
                          // 聊天气泡
                          decoration: BoxDecoration(
                            color: _msgList[index].isMe
                                ? const Color.fromARGB(255, 164, 208, 238)
                                : const Color.fromARGB(255, 153, 231, 169),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          // 消息文本
                          child: Text(
                            _msgList[index].msg,
                          ),
                        )
                      ],
                    ),
                  );
                }),
          ),
          Center(
            child: Column(
              children: [
                Container(
                  height: 0.3,
                  color: Colors.grey,
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(
                      vertical: 15.0, horizontal: 18.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Expanded(
                        flex: 1,
                        child: TextField(
                          controller: _editingController,
                          decoration: const InputDecoration(
                            //提示文字
                            hintText: "请输入要发送的消息",
                            //边框
                            border: OutlineInputBorder(),
                          ),
                        ),
                      ),
                      Container(
                        margin: const EdgeInsets.only(left: 5.0),
                        child: ElevatedButton(
                          child: const Text("发送"),
                          onPressed: () {
                            var msg = _editingController.text;
                            _sendMsg(msg);
                          },
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
